@page "/ai-recommendation/{categoryId:int}"
@namespace DaoHang.Components.Pages.AIRecommendationPage
@rendermode InteractiveServer
@using DaoHang.Services
@using DaoHang.Models
@using DaoHang.Components.Pages.AIRecommendation
@inject IWebsiteService WebsiteService
@inject ICategoryService CategoryService
@inject IAliCloudAIService AliCloudAIService
@inject IWebsiteInfoService WebsiteInfoService
@inject NavigationManager Navigation
@inject IJSRuntime JSRuntime

<PageTitle>AI智能推荐 - @(category?.Name ?? "分类")</PageTitle>

<div class="recommendation-container">
    <!-- 页面标题 -->
    <div class="recommendation-header">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <h1 class="recommendation-title">
                        <i class="bi bi-robot me-3"></i>
                        AI智能推荐
                    </h1>
                    <p class="recommendation-subtitle">
                        为"<span class="category-highlight">@(category?.Name ?? "分类")</span>"分类推荐优质网站
                    </p>
                </div>
                <div class="col-md-4 text-end">
                    <button class="btn btn-outline-light" @onclick="GoBack">
                        <i class="bi bi-arrow-left me-2"></i>返回管理
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 推荐内容区域 -->
    <div class="recommendation-content">
        <div class="container">
            @if (isLoading)
            {
                <LoadingAnimation 
                    CategoryName="@(category?.Name ?? "分类")" 
                    RecommendationCount="@recommendationCount"
                    PreferChineseWebsites="@preferChineseWebsites" />
            }
            else if (recommendedWebsites.Any())
            {
                <!-- 推荐统计 -->
                <RecommendationStats 
                    CategoryName="@(category?.Name ?? "分类")"
                    TotalCount="@recommendedWebsites.Count"
                    SelectedCount="@selectedCount"
                    AverageScore="@averageScore"
                    ChineseWebsiteCount="@GetChineseWebsiteCount()"
                    ExistingWebsitesCount="@existingWebsites.Count" />

                <!-- 推荐设置 -->
                <RecommendationSettings
                    PreferChineseWebsites="@preferChineseWebsites"
                    RecommendationCount="@recommendationCount"
                    OnPreferenceChangeCallback="@OnPreferenceChanged"
                    OnCountChangeCallback="@OnCountChanged" />

                <!-- 操作按钮 -->
                <div class="recommendation-actions">
                    <div class="d-flex justify-content-between align-items-center">
                        <div class="selection-controls">
                            <button class="btn btn-outline-primary me-2" @onclick="SelectAll">
                                <i class="bi bi-check-all me-1"></i>全选
                            </button>
                            <button class="btn btn-outline-secondary me-2" @onclick="SelectNone">
                                <i class="bi bi-x-square me-1"></i>取消全选
                            </button>
                            <button class="btn btn-outline-info" @onclick="RefreshRecommendations" disabled="@isLoading">
                                @if (isLoading)
                                {
                                    <span class="spinner-border spinner-border-sm me-1"></span>
                                    <span>推荐中...</span>
                                }
                                else
                                {
                                    <i class="bi bi-arrow-clockwise me-1"></i>
                                    <span>重新推荐</span>
                                }
                            </button>
                        </div>
                        <div>
                            <button class="btn btn-success" @onclick="ImportSelectedWebsites" disabled="@(selectedCount == 0 || isImporting)">
                                @if (isImporting)
                                {
                                    <span class="spinner-border spinner-border-sm me-1"></span>
                                    <span>导入中...</span>
                                }
                                else
                                {
                                    <i class="bi bi-check2-circle me-1"></i>
                                    <span>导入选中的网站</span>
                                }
                            </button>
                        </div>
                    </div>
                </div>

                <!-- 推荐网站列表 -->
                <div class="recommendation-list">
                    @foreach (var website in recommendedWebsites)
                    {
                        <RecommendationItem 
                            Website="@website" 
                            IsSelected="@selectedWebsites.Contains(website.Id)"
                            OnSelectionChange="@(selected => OnWebsiteSelectionChanged(website.Id, selected))" />
                    }
                </div>
            }
            else
            {
                <div class="empty-state">
                    <div class="empty-icon">
                        <i class="bi bi-emoji-frown"></i>
                    </div>
                    <h3>暂无推荐</h3>
                    <p>AI未能为该分类找到合适的推荐网站，请尝试更改设置或更换分类</p>
                    <button class="btn btn-primary" @onclick="RefreshRecommendations">
                        <i class="bi bi-arrow-clockwise me-1"></i>重新推荐
                        </button>
                </div>
            }
        </div>
    </div>
</div>

@code {
    /// <summary>
    /// 分类ID参数
    /// </summary>
    [Parameter]
    public int CategoryId { get; set; }

    /// <summary>
    /// 分类对象
    /// </summary>
    private Category? category;

    /// <summary>
    /// 推荐的网站列表
    /// </summary>
    private List<RecommendedWebsite> recommendedWebsites = new();

    /// <summary>
    /// 已存在的网站列表
    /// </summary>
    private List<Website> existingWebsites = new();

    /// <summary>
    /// 已选择的网站ID集合
    /// </summary>
    private HashSet<string> selectedWebsites = new();

    /// <summary>
    /// 是否正在加载
    /// </summary>
    private bool isLoading = true;

    /// <summary>
    /// 是否正在导入
    /// </summary>
    private bool isImporting = false;

    /// <summary>
    /// 是否优先推荐中国网站
    /// </summary>
    private bool preferChineseWebsites = true;

    /// <summary>
    /// 推荐数量
    /// </summary>
    private int recommendationCount = 15;

    /// <summary>
    /// 已选择的网站数量
    /// </summary>
    private int selectedCount => selectedWebsites.Count;

    /// <summary>
    /// 平均评分
    /// </summary>
    private double averageScore => recommendedWebsites.Any() ? recommendedWebsites.Average(w => w.Score) : 0;

    /// <summary>
    /// 组件初始化
    /// </summary>
    protected override async Task OnInitializedAsync()
    {
        await LoadCategoryAsync();
        await LoadExistingWebsitesAsync();
        await GetRecommendationsAsync();
    }

    /// <summary>
    /// 加载分类信息
    /// </summary>
    private async Task LoadCategoryAsync()
    {
        try
        {
            category = await CategoryService.GetCategoryByIdAsync(CategoryId);
            if (category == null)
            {
                // 分类不存在，返回管理页面
                Navigation.NavigateTo("/admin");
            }
        }
        catch (Exception)
        {
            // 发生异常，返回管理页面
            Navigation.NavigateTo("/admin");
        }
    }

    /// <summary>
    /// 加载现有网站
    /// </summary>
    private async Task LoadExistingWebsitesAsync()
    {
        try
        {
            existingWebsites = await WebsiteService.GetWebsitesByCategoryIdAsync(CategoryId);
        }
        catch (Exception)
        {
            existingWebsites = new List<Website>();
        }
    }

    /// <summary>
    /// 获取AI推荐网站
    /// </summary>
    private async Task GetRecommendationsAsync()
    {
        isLoading = true;
        selectedWebsites.Clear();
        recommendedWebsites.Clear();
        StateHasChanged();

        try
        {
            // 获取已存在的网站URL列表，用于排除
            var existingUrls = existingWebsites.Select(w => w.Url).ToList();

            // 调用AI服务获取推荐
            var recommendations = await AliCloudAIService.GetRecommendedWebsitesAsync(
                category?.Name ?? "",
                category?.Description ?? "",
                recommendationCount,
                preferChineseWebsites,
                existingUrls
            );

            if (recommendations?.Any() == true)
            {
                // 使用WebsiteInfoService获取网站图标
                foreach (var site in recommendations)
                {
                    try
                    {
                        var info = await WebsiteInfoService.GetIconOnlyAsync(site.Url);
                        if (!string.IsNullOrEmpty(info?.IconUrl))
                        {
                            site.IconUrl = info.IconUrl;
                        }
                    }
                    catch
                    {
                        // 忽略图标获取错误
                    }
                }

                recommendedWebsites = recommendations;
                
                // 默认全选
                SelectAll();
            }
        }
        catch (Exception)
        {
            // 处理异常
            recommendedWebsites = new List<RecommendedWebsite>();
        }
        finally
        {
            isLoading = false;
            StateHasChanged();
        }
    }

    /// <summary>
    /// 返回管理页面
    /// </summary>
    private void GoBack()
    {
        Navigation.NavigateTo("/admin");
    }

    /// <summary>
    /// 全选网站
    /// </summary>
    private void SelectAll()
    {
        selectedWebsites.Clear();
        foreach (var website in recommendedWebsites)
        {
            selectedWebsites.Add(website.Id);
        }
        StateHasChanged();
    }

    /// <summary>
    /// 取消全选
    /// </summary>
    private void SelectNone()
    {
        selectedWebsites.Clear();
        StateHasChanged();
    }

    /// <summary>
    /// 刷新推荐
    /// </summary>
    private async Task RefreshRecommendations()
    {
        await GetRecommendationsAsync();
    }

    /// <summary>
    /// 获取中国网站数量
    /// </summary>
    private int GetChineseWebsiteCount()
    {
        return recommendedWebsites.Count(w => w.IsChineseWebsite);
    }

    /// <summary>
    /// 处理偏好设置变更
    /// </summary>
    private async Task OnPreferenceChanged(bool value)
    {
        preferChineseWebsites = value;
        await RefreshRecommendations();
    }

    /// <summary>
    /// 处理推荐数量变更
    /// </summary>
    private async Task OnCountChanged(int value)
            {
        recommendationCount = value;
        await RefreshRecommendations();
    }

    /// <summary>
    /// 处理网站选择状态变更
    /// </summary>
    private void OnWebsiteSelectionChanged(string websiteId, bool selected)
    {
        if (selected)
            {
            selectedWebsites.Add(websiteId);
        }
        else
        {
            selectedWebsites.Remove(websiteId);
            }
        StateHasChanged();
    }

    /// <summary>
    /// 导入选中的网站
    /// </summary>
    private async Task ImportSelectedWebsites()
    {
        if (selectedWebsites.Count == 0)
        {
            await JSRuntime.InvokeVoidAsync("alert", "请先选择要导入的网站");
            return;
        }

        try
        {
            isImporting = true;
            StateHasChanged();

            // 准备要导入的网站列表
            var sitesToImport = recommendedWebsites
                .Where(w => selectedWebsites.Contains(w.Id))
                .Select(w => new Website
                {
                    Name = w.Name,
                    Url = w.Url,
                    Description = w.Description,
                    IconUrl = w.IconUrl,
                    CategoryId = CategoryId,
                    Tags = string.Join(",", w.Tags),
                    SortOrder = 0, // 默认排序
                    CreateTime = DateTime.Now,
                    IsRecommended = w.Score >= 4.5 // 高分网站标记为推荐
                })
                .ToList();

            // 调用服务导入网站
            int importedCount = 0;
            foreach (var site in sitesToImport)
    {
        try
        {
                    await WebsiteService.AddWebsiteAsync(site);
                    importedCount++;
        }
        catch
        {
                    // 忽略单个网站导入失败
        }
    }

            // 显示导入结果
            await JSRuntime.InvokeVoidAsync("alert", $"成功导入 {importedCount} 个网站到【{category?.Name}】分类");

            // 刷新页面
            Navigation.NavigateTo($"/admin");
        }
        catch (Exception ex)
        {
            await JSRuntime.InvokeVoidAsync("alert", $"导入失败：{ex.Message}");
        }
        finally
        {
            isImporting = false;
            StateHasChanged();
            }
    }
} 